package com.seatiger.structure.queue;

/**
 * 链表实现队列
 * @param <E>
 */
public class LinkedListQueue<E> implements Queue<E> {

    private class Node {
        private E e;
        private Node next;
        public Node(E e,Node next){
            this.e = e;
            this.next = next;
        }
        public Node(E e) {
            this(e,null);
        }
        public Node(){
            this(null,null);
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }

    private Node head,tail;
    private int size;

    public LinkedListQueue(){
        head = null;
        tail = null;
        size = 0;
    }

    /**
     * 入队从tail端插入
     * @param e
     */
    @Override
    public void enqueue(E e) {
        if (isEmpty()){
            tail = new Node(e);
            head = tail;
        }else {
            tail.next = new Node(e);
            tail = tail.next;
        }

        size++;
    }

    /**
     * 从head端出队
     * @return
     */
    @Override
    public E dequeue() {
        if (isEmpty()){
            throw new IllegalArgumentException("Dequeue fail. queue is empty");
        }
        Node dealNode = head;
        head = head.next;
        dealNode.next = null;
        if (head == null){
            tail = null;
        }
        size--;
        return dealNode.e;
    }

    @Override
    public E getFront() {
        if (isEmpty()){
            throw new IllegalArgumentException("Dequeue fail. queue is empty");
        }
        return head.e;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append("Queue front: ");
        Node cur = head;
        while (cur != null){
            res.append(cur + "->");
            cur = cur.next;
        }
        res.append("NUll tail");
        return res.toString();
    }
}
